package com.rao.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * Security 内存用户信息配置类
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/09/06 20:11
 */
@Configuration
public class UserDetailsServiceConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用推荐的密码加密类
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Bean
    public UserDetailsService userDetailsService() {

        PasswordEncoder encoder = passwordEncoder();
        // 创建内存的 UserDetailsService实现类对象
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();

        // 创建用户
        manager.createUser(User.withUsername("admin")
                .password(encoder.encode("admin"))
                .roles("ADMIN", "USER").build());

        manager.createUser(User.withUsername("user")
                .password(encoder.encode("123456"))
                .roles("USER").build());

        return manager;
    }

}
